package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.MemberPrivileges;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.service.MemberPrivilegesService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 会员特权接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/member-privileges")
@Slf4j
public class MemberPrivilegesController {

    @Resource
    private MemberPrivilegesService memberPrivilegesService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建会员特权
     *
     * @param memberPrivileges
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addMemberPrivilege(@RequestBody MemberPrivileges memberPrivileges, HttpServletRequest request) {
        if (memberPrivileges == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        // 校验必填字段
        String privilegeKey = memberPrivileges.getPrivilegeKey();
        String privilegeName = memberPrivileges.getPrivilegeName();
        if (privilegeKey == null || privilegeKey.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "特权标识不能为空");
        }
        if (privilegeName == null || privilegeName.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "特权名称不能为空");
        }
        
        User loginUser = userService.getLoginUser(request);
        
        // 设置默认值
        if (memberPrivileges.getIsActive() == null) {
            memberPrivileges.setIsActive(1);
        }
        if (memberPrivileges.getSortOrder() == null) {
            memberPrivileges.setSortOrder(0);
        }
        
        boolean result = memberPrivilegesService.save(memberPrivileges);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newMemberPrivilegeId = memberPrivileges.getId();
        return ResultUtils.success(newMemberPrivilegeId);
    }

    /**
     * 删除会员特权
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteMemberPrivilege(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        MemberPrivileges oldMemberPrivilege = memberPrivilegesService.getById(id);
        ThrowUtils.throwIf(oldMemberPrivilege == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = memberPrivilegesService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新会员特权（仅管理员）
     *
     * @param memberPrivileges
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateMemberPrivilege(@RequestBody MemberPrivileges memberPrivileges) {
        if (memberPrivileges == null || memberPrivileges.getId() == null || memberPrivileges.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "ID不能为空");
        }
        boolean result = memberPrivilegesService.updateById(memberPrivileges);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取会员特权
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<MemberPrivileges> getMemberPrivilegeById(@RequestParam long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MemberPrivileges memberPrivilege = memberPrivilegesService.getById(id);
        if (memberPrivilege == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(memberPrivilege);
    }

    /**
     * 分页获取会员特权列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MemberPrivileges>> listMemberPrivilegeByPage(@RequestParam long current, @RequestParam long size) {
        Page<MemberPrivileges> memberPrivilegePage = memberPrivilegesService.page(new Page<>(current, size));
        return ResultUtils.success(memberPrivilegePage);
    }

    /**
     * 分页获取公开的会员特权列表
     *
     * @param current
     * @param size
     * @param memberType 会员类型筛选
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<MemberPrivileges>> listPublicMemberPrivileges(
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size,
            @RequestParam(required = false) Integer memberType) {
        
        Page<MemberPrivileges> memberPrivilegePage;
        if (memberType != null) {
            memberPrivilegePage = memberPrivilegesService.lambdaQuery()
                    .eq(MemberPrivileges::getRequiredMemberType, memberType)
                    .eq(MemberPrivileges::getIsActive, 1)
                    .orderByAsc(MemberPrivileges::getSortOrder)
                    .page(new Page<>(current, size));
        } else {
            memberPrivilegePage = memberPrivilegesService.lambdaQuery()
                    .eq(MemberPrivileges::getIsActive, 1)
                    .orderByAsc(MemberPrivileges::getSortOrder)
                    .page(new Page<>(current, size));
        }
        return ResultUtils.success(memberPrivilegePage);
    }

    /**
     * 获取所有启用的会员特权
     *
     * @return
     */
    @GetMapping("/list/active")
    public BaseResponse<Page<MemberPrivileges>> listActiveMemberPrivileges() {
        Page<MemberPrivileges> memberPrivilegePage = memberPrivilegesService.lambdaQuery()
                .eq(MemberPrivileges::getIsActive, 1)
                .orderByAsc(MemberPrivileges::getSortOrder)
                .page(new Page<>(1, 100));
        return ResultUtils.success(memberPrivilegePage);
    }

    /**
     * 根据会员类型获取特权列表
     *
     * @param memberType
     * @return
     */
    @GetMapping("/list/by-type")
    public BaseResponse<Page<MemberPrivileges>> listPrivilegesByMemberType(@RequestParam Integer memberType) {
        if (memberType == null || memberType < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "会员类型参数错误");
        }
        Page<MemberPrivileges> memberPrivilegePage = memberPrivilegesService.lambdaQuery()
                .eq(MemberPrivileges::getRequiredMemberType, memberType)
                .eq(MemberPrivileges::getIsActive, 1)
                .orderByAsc(MemberPrivileges::getSortOrder)
                .page(new Page<>(1, 100));
        return ResultUtils.success(memberPrivilegePage);
    }

    /**
     * 编辑会员特权（给管理员使用）
     *
     * @param memberPrivileges
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> editMemberPrivilege(@RequestBody MemberPrivileges memberPrivileges, HttpServletRequest request) {
        if (memberPrivileges == null || memberPrivileges.getId() == null || memberPrivileges.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "ID不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        MemberPrivileges oldMemberPrivilege = memberPrivilegesService.getById(memberPrivileges.getId());
        ThrowUtils.throwIf(oldMemberPrivilege == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = memberPrivilegesService.updateById(memberPrivileges);
        return ResultUtils.success(result);
    }

    // endregion
}